/**
 * 
 */
package com.gson.inter;

import org.jdom.input.SAXBuilder;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.JDOMException;
import java.io.IOException;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;

/**
 * @作者 Stone
 * @创建日期 2013-10-18 下午03:11:21
 * @版本 V1.0
 * @类说明
 */
public class RssViewer {
	private String rss_feed;
	private String Root_Title;
	private ArrayList RSS_items = null;
	private boolean isValid = false;// 檢查rss有效性，默認為無效,解析方法成功時再設置為真值

	public RssViewer(String feed_url) throws JDOMException, IOException {

		this.rss_feed = feed_url;
		RSS_items = new ArrayList();

		try {
			this.RSS_parse();
			isValid = true;

		} catch (JDOMException jdem) {
			RssChild rsschild = new RssChild();
			rsschild.setLink("http://localhost:8080/booking/err.xml");
			rsschild.setTitle("RSS資源" + this.rss_feed + "無效");
			this.addChildItem(rsschild);

		} catch (IOException ioe) {// 重復編碼
			RssChild rsschild = new RssChild();
			rsschild.setLink("http://localhost:8080/booking/err.xml");
			rsschild.setTitle("RSS資源" + this.rss_feed + "無效");
			this.addChildItem(rsschild);
		}
	}

	public ArrayList getRSS_items() {
		return RSS_items;
	}

	private void addChildItem(RssChild child) {
		this.RSS_items.add(child);
	}

	public String getRoot_Title() {
		return Root_Title;
	}

	public void RSS_parse() throws JDOMException, IOException {// 解析rss文件內容
		Document doc;
		SAXBuilder RSS_Factory = new SAXBuilder();
		doc = RSS_Factory.build(this.rss_feed);
		Element root = doc.getRootElement();
		this.Root_Title = root.getText();
		if (this.Root_Title == null)
			throw new JDOMException();

		List Channel_child = root.getChildren();
		Element element_channel = (Element) Channel_child.iterator().next();
		List list_items = element_channel.getChildren();
		Iterator itx = list_items.iterator();// 遍曆根的子元素,一般為channel一個元素
		while (itx.hasNext()) {
			Element child = (Element) itx.next();
			if (child.getName().equals("title"))
				this.Root_Title = child.getText();
			if (child.getName().equals("item")) {
				List item_child = child.getChildren();
				Iterator itx_item = item_child.iterator();
				RssChild rsschild = new RssChild();

				while (itx_item.hasNext()) {// 遍曆每一個item對象的每一個節點
					Element item_obj = (Element) itx_item.next();
					if (item_obj.getName().equals("title")) {
						rsschild.setTitle(item_obj.getText());

					}
					if (item_obj.getName().equals("link")) {
						rsschild.setLink(item_obj.getText());
					}
					if (item_obj.getName().equals("description")) {
						rsschild.setDescription(item_obj.getTextTrim());
					}
				}
				this.addChildItem(rsschild);// 將rsschild對象壓入list對象中
			}
		}
	}

	public boolean check_Rss() {// 檢測輸入的地址是否為有效的url

		return this.isValid;
	}
}
